package com.wxlalt.rediscache.controller;

import com.wxlalt.rediscache.config.VersionCall;
import com.wxlalt.rediscache.entity.Result;
import com.wxlalt.rediscache.entity.Shop;
import com.wxlalt.rediscache.service.IShopService;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author a1615
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop")
public class ShopController implements VersionCall,IShopController {

    @Resource
    public IShopService[] shopServices;

    /**
     * 根据id查询商铺信息
     * @param id 商铺id
     * @return 商铺详情数据
     */
    @GetMapping("/{id}")
    public Result queryShopById(@PathVariable("id") Long id,@RequestHeader(value = "version",required = false)String version) {

        AtomicReference<Result> result = new AtomicReference<>(new Result());
        Optional.ofNullable(this.getServerOrDefaultByVersion(shopServices, version)).ifPresent(serve->{
            result.set(serve.queryById(id));
        });

        return result.get();
    }

    /**
     * 新增商铺信息
     * @param shop 商铺数据
     * @return 商铺id
     */
    @PostMapping
    public Result saveShop(@RequestBody Shop shop) {
        // 写入数据库
        shopServices[0].save(shop);
        // 返回店铺id
        return Result.ok(shop.getId());
    }

    /**
     * 更新商铺信息
     * @param shop 商铺数据
     * @return 无
     */
    @PutMapping
    public Result updateShop(@RequestBody Shop shop,@RequestHeader(value = "version",required = false)String version) {
        AtomicReference<Result> result = new AtomicReference<>(new Result());
        Optional.ofNullable(this.getServerOrDefaultByVersion(shopServices, version)).ifPresent(serve->{
            result.set(serve.update(shop));
        });
        // 写入数据库
        return result.get();
    }
}
